const app = getApp();
const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
const user = require('../../../utils/user.js');

Page({
    data: {
        phone: '',
        code: '',
        countDown: 0,
        agreed: true,
        userInfo: {},
        // hasLogin: false,
        submitting: false
    },

    onLoad: function(options) {
        // 获取用户信息和登录状态
        let userInfo = wx.getStorageSync('userInfo');
        // let token = wx.getStorageSync('token');
        console.log(userInfo)
        this.setData({
            userInfo: userInfo || {},
            // hasLogin: !!token
        });
    },

    onReady: function() {
        // 页面初次渲染完成
    },

    onShow: function() {
        // 页面显示
    },

    // 返回上一页
    goBack: function() {
        wx.navigateBack({
            delta: 1
        });
    },

    // 切换协议同意状态
    toggleAgreement: function() {
        this.setData({
            agreed: !this.data.agreed
        });
    },

    // 查看用户协议
    showUserAgreement: function() {
        wx.navigateTo({
            url: '/pages/ucenter/agreement/agreement?type=user'
        });
    },

    // 查看隐私政策
    showPrivacyPolicy: function() {
        wx.navigateTo({
            url: '/pages/ucenter/agreement/agreement?type=privacy'
        });
    },

    // 输入手机号
    inputPhone: function(e) {
        this.setData({
            phone: e.detail.value
        });
    },

    // 输入验证码
    inputCode: function(e) {
        this.setData({
            code: e.detail.value
        });
    },

    // 获取验证码
    getCode: function() {
        if (this.data.countDown > 0) {
            return;
        }

        if (!this.data.agreed) {
            wx.showToast({
                title: '请先同意用户协议和隐私政策',
                icon: 'none'
            });
            return;
        }

        if (!this.data.userInfo) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });

            setTimeout(() => {
                wx.navigateTo({
                    url: '/pages/auth/login/login'
                });
            }, 1000);
            return;
        }

        const phone = this.data.phone;
        if (!phone || phone.length !== 11) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            });
            return;
        }

        // 显示加载中
        wx.showLoading({
            title: '发送中...',
            mask: true
        });

        // 调用发送验证码API
        util.request(api.AuthSendCaptcha, {
            phone: phone
        }, 'POST').then(res => {
            wx.hideLoading();
            if (res.code === 200) {
                wx.showToast({
                    title: '验证码已发送',
                    icon: 'success'
                });
                this.startCountDown();
            } else {
                wx.showToast({
                    title: res.errmsg || '发送失败，请重试',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            wx.showToast({
                title: '发送失败，请重试',
                icon: 'none'
            });
            console.error(err);
        });
    },

    // 倒计时
    startCountDown: function() {
        this.setData({
            countDown: 60
        });

        const timer = setInterval(() => {
            if (this.data.countDown <= 1) {
                clearInterval(timer);
                this.setData({
                    countDown: 0
                });
                return;
            }

            this.setData({
                countDown: this.data.countDown - 1
            });
        }, 1000);

        this.countDownTimer = timer;
    },

    // 提交绑定
    submitBind: function() {
        if (!this.data.agreed) {
            wx.showToast({
                title: '请先同意用户协议和隐私政策',
                icon: 'none'
            });
            return;
        }

        if (!this.data.userInfo) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });

            setTimeout(() => {
                wx.navigateTo({
                    url: '/pages/auth/login/login'
                });
            }, 1000);
            return;
        }

        const { phone, code } = this.data;

        if (!phone || phone.length !== 11) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            });
            return;
        }

        if (!code || code.length < 4) {
            wx.showToast({
                title: '请输入正确的验证码',
                icon: 'none'
            });
            return;
        }

        // 防止重复提交
        if (this.data.submitting) {
            return;
        }

        this.setData({
            submitting: true
        });

        wx.showLoading({
            title: '绑定中...',
            mask: true
        });

        // 调用绑定手机号API
        console.log(this.data.phone)
        console.log(this.data.code)
        console.log(this.data.userInfo.weixinOpenid)
        util.request(api.AuthBindPhone, {
            phone: this.data.phone,
            code: this.data.code,
            openid: this.data.userInfo.weixinOpenid
        }, 'POST').then(res => {
            wx.hideLoading();
            if (res.errno === 0) {
                // 更新用户信息
                let userInfo = wx.getStorageSync('userInfo') || {};
                userInfo.phone = phone;
                wx.setStorageSync('userInfo', userInfo);

                wx.showToast({
                    title: '手机绑定成功',
                    icon: 'success'
                });

                // 延迟返回，确保提示能看到
                setTimeout(() => {
                    // 返回个人中心页面
                    wx.switchTab({
                        url: '/pages/ucenter/index/index'
                    });
                }, 1500);
            } else {
                this.setData({
                    submitting: false
                });

                wx.showToast({
                    title: res.errmsg || '绑定失败，请重试',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            this.setData({
                submitting: false
            });

            wx.showToast({
                title: '绑定失败，请重试',
                icon: 'none'
            });
            console.error(err);
        });
    },

    onUnload: function() {
        // 清除倒计时定时器
        if (this.countDownTimer) {
            clearInterval(this.countDownTimer);
        }
    }
})